from flask import Blueprint, request, jsonify
from models import db, WorkExperience

work_experience_bp = Blueprint('work_experience', __name__)

@work_experience_bp.route('/api/employees/<int:employee_id>/work_experiences', methods=['GET'])
def get_work_experiences(employee_id):
    work_experiences = WorkExperience.query.filter_by(employee_id=employee_id).order_by(WorkExperience.start_date.desc()).all()
    return jsonify([work_experience.to_dict() for work_experience in work_experiences])

@work_experience_bp.route('/api/employees/<int:employee_id>/work_experiences', methods=['POST'])
def create_work_experience(employee_id):
    data = request.get_json()
    data['employee_id'] = employee_id
    experience = WorkExperience(**data)
    db.session.add(experience)
    db.session.commit()
    return jsonify({'message': '创建成功', 'id': experience.id}), 201

@work_experience_bp.route('/api/employees/<int:employee_id>/work_experiences/<int:id>', methods=['PUT'])
def update_work_experience(employee_id, id):
    experience = WorkExperience.query.filter_by(id=id, employee_id=employee_id).first_or_404()
    data = request.get_json()
    for key, value in data.items():
        setattr(experience, key, value)
    db.session.commit()
    return jsonify({'message': '修改成功'})

@work_experience_bp.route('/api/employees/<int:employee_id>/work_experiences/<int:id>', methods=['DELETE'])
def delete_work_experience(employee_id, id):
    experience = WorkExperience.query.filter_by(id=id, employee_id=employee_id).first_or_404()
    db.session.delete(experience)
    db.session.commit()
    return jsonify({'message': '删除成功'}) 